import React from "react";

import { Link} from 'react-router-dom';

import PageContent from '../../PageContent'

import { ajax ,showResultMessage,isNull,setStoreItem,getStoreItem, isNotNull} from '../../common';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UICardTabs from '../../uicomponents/UICardTabs';

import UIFormView from '../../uicomponents/UIFormView';

import UIToolbar from '../../uicomponents/UIToolbar';

import ImportProductUIActionPanel from './ImportUIDataFilePanel';

import ExportProductUIActionPanel from './ExportUIDataFilePanel';


/** 
 * UIAction管理应用入口
*/
export default class ProductUIActionManageApp extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
			actionGroupSearchValues : getStoreItem('actionGroupSearchValues',{}),
			actionSearchValues : getStoreItem('actionGroupSearchValues',{}),
        };
	}
	
	onTabChange = (tabName) => {
        this.activeTabKey = tabName;
	}
	
	onActionGroupSearchValueChange = (values) => {
		this.setState({actionGroupSearchValues : values});
		setStoreItem('actionGroupSearchValues',values);
	}

	onActionSearchValueChange = (values) => {
		this.setState({actionSearchValues : values});
		setStoreItem('actionSearchValues',values);
	}

    render() {

		/**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUIActionTabsPanel {...props} 
						activeTabKey={this.activeTabKey}
						actionGroupSearchValues={this.state.actionGroupSearchValues} 
						onActionGroupSearchValueChange={this.onActionGroupSearchValueChange}
						actionSearchValues={this.state.actionSearchValues} 
						onActionSearchValueChange={this.onActionSearchValueChange} 
						onTabChange={this.onTabChange} 
						key="uiActionTabs" 
						
						/>
						);
				}
			},
			'/editRelatedActions': {
				text: '编辑关联动作',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIActionGroupPanel {...props} key="editActionGroup" />);
				}
			},
			'/editSubActions': {
				text: '编辑关联动作',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIActionPanel {...props} key="editAction" />);
				}
			},
			'/importDataFiles': {
				text: '导入UI动作',
				icon: 'sign-in-alt',
                getComponent: (owner, props) => {
                    return <ImportProductUIActionPanel {...props} importURL="PRODUCT/UI/import/importUIActionFile/" pageTitle="导入UI动作" key="importActions"/>;
                }
			},
			'/exportDataFiles': {
				text: '导出UI动作',
				icon: 'sign-out-alt',
                getComponent: (owner, props) => {
                    return <ExportProductUIActionPanel {...props} exportURL="PRODUCT/UI/export/exportUIActionFile/" pageTitle="导出UI动作" key="exportActions"/>;
                }
			},
		};


        return (
            <PageContent pageInstance={this} contentMap={pageContentMap} {...this.props}>

            </PageContent>
        );
    }
};

/** 
 *产品UI动作管理
*/
class ProductUIActionTabsPanel extends React.Component {

    onTabChange = (tabName) => {
        switch (tabName) {
            case 'actionGroupInfo':
                this.actionGroupListRef.loadActionGroups();
                break;
            case 'actionInfo':
                this.actionListRef.loadActions();
                break;
		}
		
		if(this.props.onTabChange !== undefined){
            this.props.onTabChange(tabName);
        }
	}

	actionHandler = (actionEvent) => {

		return {
			
		}
	}


	render() {
		const pageHistory = this.props.history;
        const tabPanelContentMap = {
			
            '/ProductUIActionGroupListPanel': {
                getComponent: (owner, props) => {
					console.log(this.props.actionGroupSearchValues);
                    return <ProductUIActionGroupListPanel searchValues={this.props.actionGroupSearchValues} onSearchValueChange={this.props.onActionGroupSearchValueChange} {...props} pageHistory={pageHistory} ref={(inst) => this.actionGroupListRef = inst}/>;
                }
            },
            '/ProductUIActionListPanel': {
                getComponent: (owner, props) => {
                    return <ProductUIActionListPanel searchValues={this.props.actionSearchValues} onSearchValueChange={this.props.onActionSearchValueChange} {...props} pageHistory={pageHistory} ref={(inst) => this.actionListRef = inst}/>;
                }
			},
			
			
        };


		return (
			<UICardTabs
				title="UI动作列表"
				activeTabKey={this.props.activeTabKey}
                tabConfigId="uiActionListTab"
                onTabChange={this.onTabChange}
				tabContentMap={tabPanelContentMap}
				extra={<UIToolbar history={pageHistory} actionGroupId="productUIDataPanelActionGroup" actionHandler={this.actionHandler}/>}
            />
		);
	}
}

/**
 * 动作组
 */
class ProductUIActionGroupListPanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			searchValues : props.searchValues,
		}
		//console.log( props.searchValues);
    }
    
    loadActionGroups = () => {
        this.actionGroupListRef.loadData();
    }

	actionHandler = (actionEvent) => {

		const { selectIds, actionGroupListRef, actionGroupFormRef } = this;

		return {
			refresh : () => {
				actionGroupListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增产品动作组'});
				setTimeout(() => {
					actionGroupFormRef.openModal(() => {
						const initParams = getStoreItem('actionGroupSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							actionGroupFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑产品动作组' });
				setTimeout(() => {
					actionGroupFormRef.openModal(() => {
						actionGroupFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIActionGroup/batchDelete', { ids: selectedIds }, (data) => {
					actionGroupListRef.loadData();
				});
			},
			doSave : () => {
				actionGroupFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUIActionGroup/save', formData, (data) => {
						actionGroupFormRef.closeModal();
						actionGroupListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
			bordered : false,
			history : this.props.pageHistory,
			ref: (inst) => { this.actionGroupListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIActionGroupListActionGroup',
			rowActionGroupId: 'productUIActionGroupRowActionGroup',
			tableConfigId: 'productUIActionGroupTable',
			dataUrl: 'PRODUCT/UI/productUIActionGroup/query',
			selectMode: 'multi',
			searchFormId: 'productUIActionGroupSearchForm',
			initSearchValues : this.props.searchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
			onSearchData : (changedValues) => {
				
				if(this.props.onSearchValueChange){
					this.props.onSearchValueChange(changedValues)
				}
			}
		};

		const formProps = {
			ref: (inst) => { this.actionGroupFormRef = inst },
			formConfigId: 'productUIActionGroupForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 动作项
 */
class ProductUIActionListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
		}
    }

    loadActions = () => {
        this.actionListRef.loadData();
    }

    actionHandler = (actionEvent) => {

		const { selectIds, actionListRef, actionFormRef } = this;

		return {
			refresh : () => {
				actionListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增产品动作'});
				setTimeout(() => {
					actionFormRef.openModal(() => {
						const initParams = getStoreItem('actionSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							actionFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑产品动作' });
				setTimeout(() => {
					actionFormRef.openModal(() => {
						actionFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIAction/batchDelete', { ids: selectedIds }, (data) => {
					actionListRef.loadData();
				});
			},
			doSave : () => {
				actionFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUIAction/save', formData, (data) => {
						actionFormRef.closeModal();
						actionListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
			bordered : false,
			history : this.props.pageHistory,
			ref: (inst) => { this.actionListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIActionListActionGroup',
			rowActionGroupId: 'productUIActionRowActionGroup',
			tableConfigId: 'productUIActionTable',
			dataUrl: 'PRODUCT/UI/productUIAction/query',
			selectMode: 'multi',
			searchFormId: 'productUIActionSearchForm',
			initSearchValues : this.props.searchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
			onSearchData : (changedValues) => {
				
				if(this.props.onSearchValueChange){
					this.props.onSearchValueChange(changedValues)
				}
			}
		};

		const formProps = {
			ref: (inst) => { this.actionFormRef = inst },
			formConfigId: 'productUIActionForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 编辑ActionGroup关联动作
 */
class EditProductUIActionGroupPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
		}
	}
	
	componentDidMount(){
		this.actionGroup = this.props.location.state;
		this.setState({pageTitle : '编辑' + this.actionGroup.actionGroupCode +   '关联动作'});
		this.loadRefActions(this.actionGroup.id);
	}

    loadRefActions = (actionGroupId) => {
		
        this.actionListRef.loadData({actionGroupId : actionGroupId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds, actionListRef, actionFormRef,chooseUIActionRef,selectRelatedActionIds,actionGroup } = this;

		return {
			refresh : () => {
				actionListRef.loadData({actionGroupId :actionGroup.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加动作'});
				setTimeout(() => {
					//actionFormRef.openModal();
					chooseUIActionRef.openModal();
				});
			},
			addRelatedItems : () => {
				
				ajax('PRODUCT/UI/productUIActionGroupRelate/addUIActionRelate', {actionGroupId : actionGroup.id, relatedActionIds: selectRelatedActionIds }, (data) => {
					chooseUIActionRef.closeModal();
					actionListRef.loadData({actionGroupId :actionGroup.id});
				});
			},
			cancelChoose : () => {
				chooseUIActionRef.closeModal();
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑动作' });
				setTimeout(() => {
					actionFormRef.openModal(() => {
						actionFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIActionGroupRelate/batchDelete', { ids: selectedIds }, (data) => {
					actionListRef.loadData({actionGroupId :actionGroup.id});
				});
			},
			doSave : () => {
				actionFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUIActionGroupRelate/save', formData, (data) => {
						actionFormRef.closeModal();
						actionListRef.loadData({actionGroupId :actionGroup.id});
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < actionListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUIActionGroupRelate/save',rowData,(data) => {
						actionListRef.loadData({actionGroupId :actionGroup.id});
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUIActionGroupRelate/save',rowData,(data) => {
						actionListRef.loadData({actionGroupId :actionGroup.id});
					});
				}
			},
			
		};
	}

	render () {
		const tableProps = {
			bordered : false,
			title : this.state.pageTitle,
			ref: (inst) => { this.actionListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIActionGroupRelateActionListActionGroup',
			rowActionGroupId: 'productUIActionGroupRelateActionRowActionGroup',
			tableConfigId: 'productUIActionGroupRelateActionTable',
			dataUrl: 'PRODUCT/UI/productUIActionGroupRelate/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		const formProps = {
			ref: (inst) => { this.actionFormRef = inst },
			formConfigId: 'productUIActionGroupRelatedActionForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		const chooseUIActionTableProps = {
			bordered: false,
			title : "选择关联动作",
			width : 1200,
			ref: (inst) => { this.chooseUIActionRef = inst },
			actionGroupId: 'chooseRelatedItemListActionGroup',
			tableConfigId: 'chooseProductUIActionTable',
			dataUrl: 'PRODUCT/UI/productUIAction/query',
			selectMode: 'multi',
			searchFormId: 'productUIActionSearchForm',
			actionHandler : this.actionHandler,
			inPop : true,
            autoLoad : true,
            destroyOnClose : true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('ok');
				} else {
					topToolBar.disable('ok');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectRelatedActionIds = selectRowKeys;
				}
			,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView {...formProps} />
				<UIDataTableView {...chooseUIActionTableProps}>
				</UIDataTableView>
			</UIDataTableView>
		);
	}
}

/**
 * 编辑Action子动作
 */
class EditProductUIActionPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
		}
	}
	
	componentDidMount(){
		this.action = this.props.location.state;
		this.setState({ pageTitle : '编辑' + this.action.code  + '子动作'  });
		this.loadSubActions(this.action.id);
	}

    loadSubActions = (actionId) => {
		
        this.actionListRef.loadData({parentId : actionId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds, actionListRef, actionFormRef,action } = this;

		return {
			refresh : () => {
				actionListRef.loadData({parentId :action.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加子动作'});
				actionFormRef.setFormData({});
				setTimeout(() => {
					actionFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑子动作' });
				setTimeout(() => {
					actionFormRef.openModal(() => {
						actionFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUIAction/batchDelete', { ids: selectedIds }, (data) => {
					actionListRef.loadData({parentId :action.id});
				});
			},
			doSave : () => {
				actionFormRef.getFormData((formData) => {
					formData.parentId = action.id;
					ajax('PRODUCT/UI/productUIAction/save', formData, (data) => {
						actionFormRef.closeModal();
						actionListRef.loadData({parentId :action.id});
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < actionListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUIAction/save',rowData,(data) => {
						actionListRef.loadData({parentId :action.id});
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUIAction/save',rowData,(data) => {
						actionListRef.loadData({parentId :action.id});
					});
				}
			},
			
		};
	}

	render () {
		const tableProps = {
			bordered : false,
			title : this.state.pageTitle,
			ref: (inst) => { this.actionListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUISubActionListActionGroup',
			rowActionGroupId: 'productUISubActionRowActionGroup',
			tableConfigId: 'productUISubActionTable',
			dataUrl: 'PRODUCT/UI/productUIAction/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		const formProps = {
			ref: (inst) => { this.actionFormRef = inst },
			formConfigId: 'productUISubActionForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
	}
}